package com.youtui.manager.controller;

import java.io.IOException;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.youtui.common.constant.ResultMessage;
import com.youtui.common.util.ResultUtil;
import com.youtui.manager.model.Opter;
import com.youtui.manager.service.IOpterService;

@Controller
public class LoginController extends BaseController {

	@Autowired
	IOpterService opterService;

	@RequestMapping("/login.do")
	@ResponseBody
	public ResultMessage login(String username, String password) throws IOException {
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(username, password);
		// 认证
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			return ResultUtil.result(ResultUtil.code_fail, "用户名不存在");
		} catch (IncorrectCredentialsException e) {
			return ResultUtil.result(ResultUtil.code_fail, "用户名或密码错误");
		} catch (Exception e) {
			return ResultUtil.result(ResultUtil.code_fail, "用户名或密码错误");
		}
		Opter opter = opterService.clear(opterService.findOpterByLoginName(username));
		return ResultUtil.result(ResultUtil.code_success, "登录成功", opter);
	}

	@RequestMapping("/loginout.do")
	@ResponseBody
	public ResultMessage loginout() throws IOException {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return ResultUtil.result(ResultUtil.code_success, "退出成功");
	}

}
